﻿Public Class BreadcrumbLabel
  Private _dpiFactor As Single = 0.0F


  Public Sub New()
    InitializeComponent()
    Me._dpiFactor = Me.AutoScaleDimensions.Height / 192.0F
  End Sub

  Public Sub SetBreadcrumbTextFromStack(ByVal stk As Stack(Of String))
    Dim first As Boolean = True
    Dim del As String = " " & Language.GetLanguageString("BreadcrumbDelimiter").Trim & " "

    Me.Text = String.Empty

    For Each str As String In stk.Reverse
      If Not first Then
        Me.Text &= del
      Else
        first = False
      End If

      Me.Text &= str
    Next

    Me.InvalidateSmart()
  End Sub

  Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
  End Sub

  Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    Static Dim bufWidth As Integer = 0
    Static Dim bufHeight As Integer = 0
    Static Dim buffer As Bitmap = Nothing
    Static Dim bufRect As Rectangle = Rectangle.Empty
    Static Dim brBg As New SolidBrush(Me.BackColor)
    Static Dim brFg As New SolidBrush(Me.ForeColor)

    If Me.Height > 0 Then
      If buffer Is Nothing OrElse Me.Width <> bufWidth OrElse Me.Height <> bufHeight Then
        ' Setup back buffer
        bufWidth = Me.Width
        bufHeight = Me.Height

        If buffer IsNot Nothing Then
          buffer.Dispose()
        End If

        ' Buffer
        buffer = New Bitmap(bufWidth, bufHeight)
        bufRect = New Rectangle(0, 0, bufWidth, bufHeight)
      End If
    End If

    ' Create temporary graphics buffer
    Dim g As Graphics = Graphics.FromImage(buffer)

    ' Draw the background
    g.FillRectangle(brBg, 0, 0, bufWidth, bufHeight)

    ' Draw the text
    With g.MeasureString(Me.Text, Me.Font)
      Dim xPos As Integer = 10 * Me._dpiFactor
      If .Width + xPos > bufWidth - xPos Then
        xPos = bufWidth - (.Width + xPos)
      End If
      g.DrawString(Me.Text, Me.Font, brFg, xPos, (Me.Height - .Height) >> 1)
    End With

    ' Draw the back buffer to the front
    g.Dispose()
    e.Graphics.DrawImage(buffer, 0, 0)
  End Sub

  Public Sub InvalidateSmart()
    Me.TimerInvalidate.Enabled = True
  End Sub

  Private Sub TimerInvalidate_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerInvalidate.Tick
    Me.TimerInvalidate.Enabled = False
    Me.Invalidate()
  End Sub
End Class
